import config from '@/config'
import useImage from '../useImage'
import { AbstractCanvas } from './AbstractCanvas'

export interface AcrossConfig {
  acrossName: string
  acrossY: number
  x: number
  y: number
}

export class AcrossCanvas extends AbstractCanvas {
  constructor(
    private canvas: HTMLCanvasElement,
    ctx: CanvasRenderingContext2D,
    private width: number,
    private height: number,
    private startY: number,
    private margin: number,
    private lst_acrossConfig: AcrossConfig[],
  ) {
    super(ctx)
    this.init()
  }

  // 初始化
  private init() {
    this.canvas.width = this.width
    this.canvas.height = this.height
    this.ctx.translate(this.margin, this.height - this.margin)
    this.ctx.translate(0, this.startY)
    this.ctx.scale(1, -1)
  }

  // 绘制控制点
  public async draw() {
    const { image, loadImages } = useImage()
    await loadImages(config.across)
    this.lst_acrossConfig.forEach((acrossConfig) => {
      this.ctx.save()
      this.ctx.translate(acrossConfig.x, acrossConfig.y)
      this.ctx.scale(1, -1)
      this.drawAcrossXY()
      this.drawAcrossImg(acrossConfig, image)
      this.drawAcrossText(acrossConfig)
      this.ctx.restore()
    })
  }

  private drawAcrossXY = () => {
    super.drawline([-6, 0], [6, 0], 2, 'black')
    super.drawline([0, 6], [0, -6], 2, 'black')
    super.drawCircle([0, 0], 6, 'red')
  }

  private drawAcrossImg(acrossConfig: AcrossConfig, image: Map<mapkey, HTMLImageElement>) {
    this.ctx.translate(-10, 10)
    if (acrossConfig.acrossName.includes('树')) super.drawImage(image.get('tree')!, [0, 0], 20, 20)
    else if (acrossConfig.acrossName.includes('地')) super.drawImage(image.get('field')!, [0, 0], 20, 20)
    else if (acrossConfig.acrossName.includes('线')) super.drawImage(image.get('xianlu')!, [0, 0], 20, 20)
    else if (acrossConfig.acrossName.includes('网')) super.drawImage(image.get('wang')!, [0, 0], 20, 20)
    else super.drawImage(image.get('field')!, [0, 0], 20, 20)
  }

  private drawAcrossText = (across: AcrossConfig) => {
    this.ctx.translate(24, 10)
    super.drawText(across.acrossName, [0, 0], 'black', 'left', 'bottom')
    this.ctx.translate(0, 15)
    super.drawText(across.acrossY.toString() + 'm', [0, 0], '#8CABD9', 'left', 'bottom')
  }
}
